﻿



create proc Products.SaveVendor (
	@VendorID		uniqueidentifier = null output,
	@OrgKey		int,	
	@ErrorMessage	nvarchar(400) output
)
as
begin

	if @VendorID is null
	begin
		select @VendorID = NEWID();
	end
	
	if IsNull(@OrgKey,0) = 0
	begin
		set @ErrorMessage = 'OrgKey ist null oder leer';
		goto EndWithError;
	end
	
	
	begin tran;
	
	
	
	with src 
	as
	(
		Select	@VendorID 'VendorID',
				@OrgKey 'OrgKey'
	)
	
	merge Products.datVendor as target
	using src
		on (target.VendorID = src.VendorID)
	when matched then 
		update SET	
				OrgKey		= src.OrgKey
				
	when not matched by target then
		insert (
			VendorID,
			OrgKey
		)
		values (
			src.VendorID,
			src.OrgKey
		);
		
	
	commit;
	return 0;
	
EndWithError:
	RAISERROR ( @ErrorMessage, 16, 1);
	return 1;	

end
GO


